<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '修改分类' : '添加分类' }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <div class="flex-column-between height83">
            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     label-width="100px">
              <el-form-item label="菜单名:"
                            prop="menuName">
                <el-input clearable
                          :maxlength="100"
                          v-model="form.menuName"
                          placeholder="请输入公众号菜单名">
                </el-input>
              </el-form-item>
              <el-form-item label="消息类型:"
                            prop="messageType">
                <el-radio-group v-model="form.messageType">
                  <el-radio :label="1"
                            value="1"
                            checked="true">跳转网页</el-radio>
                  <el-radio :label="2"
                            value="2">跳转小程序</el-radio>

                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.messageType==2"
                            label="小程序名称:"
                            prop="appletName">
                <el-input clearable
                          :maxlength="100"
                          v-model="form.appletName"
                          placeholder="请输入小程序名称">
                </el-input>
              </el-form-item>
              <el-form-item label="跳转网址:"
                            prop="url">
                <el-input clearable
                          :maxlength="100"
                          v-model="form.url"
                          placeholder="请输入跳转网址">
                </el-input>
              </el-form-item>

              <!-- 提交图片 -->

            </el-form>

            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">确定</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import { getToken } from '@/utils/token-util';
import {
  userOssSignature,
  qnyOssSignature
} from '@/api/creatCenter/material';
import { storageConfigDetail } from '@/api/storageInfo/index';

import axios from 'axios';
import {
  accountMenuBarModify,
  accountMenuBarInsert
} from '@/api/accountMenuBar/index';

export default {
  name: 'pictureEdit',
  components: { ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    // const categoryImage = (rule, value, callback) => {
    //   console.log(this.form.categoryImages);
    //   if (!this.form.categoryImages) {
    //     callback(new Error('请上传图片'));
    //   } else {
    //     callback();
    //   }
    // };
    const DEFAULT_FORM = {
      // 菜单名
      menuName: '',
      // 消息类型
      messageType: 1,
      url: '',
      // 站点id
      siteId: this.$store.state.site.info.id
    };
    return {
      storageMode: '',
      options: [],
      imageUrl: '',
      imgViewArr: [],
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        classificationName: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ],
        notShow: [
          {
            required: true,
            message: '请输入是否展示状态',
            trigger: 'blur'
          }
        ],

        sortByCategory: [
          {
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        // categoryImages: [
        //   { required: true, validator: categoryImage, trigger: 'change' }
        // ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false
    };
  },
  activated () {
    this.storageConfig();
  },
  methods: {
    // 获取存储配置
    async storageConfig () {
      const res = await storageConfigDetail();

      //   console.log(res.storageMode);

      this.storageMode = res?.storageMode;
    },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    // async handleFileChange (file, fileList) {
    //   console.log(this.storageMode);
    //   if (this.storageMode == 2) {
    //     this.aliFn(file, fileList);
    //   } else if (this.storageMode == 3) {
    //     this.qnyFn(file, fileList);
    //   }
    // },
    // 阿里云
    async aliFn (file, fileList) {
      this.loading = true;
      const res = await userOssSignature();
      let files = file.raw;
      let filename = file.name;
      let markIndex = filename.lastIndexOf('.');
      let suffix = filename.substring(markIndex);
      let date = new Date().getTime();
      // 构建请求参数
      let param = new FormData();
      param.append('key', date + suffix);
      param.append('policy', res.policy);
      param.append('OSSAccessKeyId', res.accessId);
      param.append('success_action_status', '200');
      // param.append("callback",  this.data.callback)     //回调（not)
      param.append('signature', res.signature);
      param.append('file', files, files.name);
      param.append('success_action_status', '200');
      let config = {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'x-oss-callback-Authorization': getToken()
        }
      };
      console.log('suffix', suffix);

      let result = await axios.post(res.host, param, config);
      let url = res.host + '/' + date + suffix;
      console.log(url);
      this.form.categoryImages = url;
      this.imageUrl = url;
      this.loading = false;
    },
    async qnyFn (file, fileList) {
      this.loading = true;
      console.log(file, fileList);

      let files = file.raw;
      console.log(files);
      //   // 构建请求参数
      let param = new FormData();

      param.append('file', files, files.name);
      param.append('getsize', files.size);
      param.append('getContentType', files.type);
      param.append('getoriginalfilename', files.name);
      param.append('getName', files.name);

      const res = await qnyOssSignature(param);
      console.log(res.url);
      this.form.categoryImages = res.url;
      this.imageUrl = res.url;
      console.log('上传图片成功=======', res);
      this.loading = false;
    },
    // 点击按钮预览图片
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        // this.form.categoryImages = this.imageUrl;
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;

        const saveOrUpdate = this.isUpdate
          ? accountMenuBarModify
          : accountMenuBarInsert;
        saveOrUpdate(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg);
            if (!this.isUpdate) {
              this.$router.go(0);
            }
            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.form.id = '';
            this.$util.assignObject(this.form, {
              ...this.data
            });
            // if (this.form.categoryImages) {
            //   this.imageUrl = this.form.categoryImages;
            //   let markIndex = this.form.categoryImages.lastIndexOf('.');
            //   let suffix = this.form.categoryImages.substring(markIndex);
            //   if (!this.fileList.length) {
            //     this.fileList.push({
            //       name: suffix,
            //       url: this.form.categoryImages
            //     });
            //   } else {
            //     this.fileList = [
            //       {
            //         name: suffix,
            //         url: this.form.categoryImages
            //       }
            //     ];
            //   }
            // } else {
            //   this.fileList = [];
            // }
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
          this.fileList = [];
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
